<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>假冒侵权智能识别系统</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* 商标详情模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: #fff;
            margin: 2% auto;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            position: absolute;
            right: 20px;
            top: 10px;
        }
        
        .close:hover {
            color: black;
        }
        
        .trademark-list {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .trademark-item {
            display: flex;
            padding: 20px;
            border-bottom: 1px solid #eee;
        }
        
        .trademark-item:last-child {
            border-bottom: none;
        }
        
        .trademark-image {
            flex: 0 0 120px;
            height: 120px;
            margin-right: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .trademark-image img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .trademark-info {
            flex: 1;
        }
        
        .trademark-info h3 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .info-row {
            margin-bottom: 8px;
        }
        
        .info-label {
            font-weight: bold;
            color: #3498db;
            display: inline-block;
            width: 80px;
        }
        
        .loading-more {
            text-align: center;
            padding: 15px;
            display: none;
        }
        
        .error {
            color: #e74c3c;
            text-align: center;
            padding: 20px;
        }
        
        .no-results {
            text-align: center;
            padding: 40px 20px;
            color: #7f8c8d;
        }
        
        .scroll-to-top {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            display: none;
        }
        
        .scroll-to-top:hover {
            background-color: #2980b9;
        }
        
        /* 商标详情模态框在移动端的样式 */
        @media (max-width: 768px) {
            .trademark-item {
                flex-direction: column;
            }
            
            .trademark-image {
                flex: 0 0 auto;
                height: auto;
                margin-right: 0;
                margin-bottom: 15px;
            }
            
            .info-label {
                width: auto;
                display: inline-block;
                margin-right: 5px;
            }
        }
        
        .view-details {
            font-size: 0.8em;
            color: #3498db;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>假冒侵权智能识别系统</h1>
        </header>
        
        <main>
            <div class="upload-section">
                <div class="upload-area" id="uploadArea">
                    <p>点击选择图片或拖拽图片到此处</p>
                    <input type="file" id="fileInput" accept="image/*" style="display: none;">
                </div>
                <button id="uploadBtn">选择图片</button>
                <button id="submitBtn" disabled>提交识别</button>
            </div>
            
            <div class="loading" id="loading" style="display: none;">
                <p>正在识别中，请稍候...</p>
            </div>
            
            <div class="results-section" id="resultsSection" style="display: none;">
                <h2>识别结果</h2>
                <div class="results-list" id="resultsList">
                    <!-- 结果将在这里动态添加 -->
                </div>
            </div>
        </main>
    </div>
    
    <!-- 商标详情模态框 -->
    <div id="trademarkModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>商标详情</h2>
            <div class="loading" id="modalLoading">
                <p>正在加载商标信息...</p>
            </div>
            
            <div class="loading-more" id="modalLoadingMore">
                <p>正在加载更多数据...</p>
            </div>
            
            <div class="error" id="modalError" style="display: none;"></div>
            
            <div class="trademark-list" id="modalTrademarkList" style="display: none;">
                <!-- 商标列表将在这里显示 -->
            </div>
        </div>
    </div>
    
    <button class="scroll-to-top" id="scrollToTop" title="回到顶部">↑</button>
    
    <script src="script.js"></script>
    <script>
        // 全局变量
        let trademarkName = '';
        let allTrademarks = []; // 缓存所有商标数据
        let currentPage = 1;
        const pageSize = 40; // 每页显示40条数据
        let isLoading = false;
        let hasMore = true;
        let scrollPosition = 0; // 保存滚动位置
        
        // 获取模态框元素
        const modal = document.getElementById("trademarkModal");
        const span = document.getElementsByClassName("close")[0];
        const scrollToTopButton = document.getElementById('scrollToTop');
        const modalContent = document.querySelector('.modal-content');
        
        // 点击 <span> (x) 按钮关闭模态框
        span.onclick = function() {
            modal.style.display = "none";
        }
        
        // 点击模态框外部关闭模态框
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
        
        // 回到顶部按钮事件
        scrollToTopButton.addEventListener('click', () => {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
        
        // 监听滚动事件
        window.addEventListener('scroll', () => {
            // 显示或隐藏回到顶部按钮
            if (window.scrollY > 300) {
                scrollToTopButton.style.display = 'block';
            } else {
                scrollToTopButton.style.display = 'none';
            }
        });
        
        // 监听模态框内容滚动事件，实现无限滚动
        modalContent.addEventListener('scroll', () => {
            // 检查是否需要加载更多数据
            const scrollHeight = modalContent.scrollHeight;
            const scrollTop = modalContent.scrollTop;
            const clientHeight = modalContent.clientHeight;
            
            // 当滚动到距离底部50px以内时加载更多
            if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading && hasMore) {
                loadMoreTrademarks();
            }
        });
        
        // 显示商标详情模态框
        function showTrademarkDetails(name, imageBase64 = '') {
            // 如果有图片数据，则使用新的联合搜索API
            if (imageBase64) {
                searchTrademarkWithImage(name, imageBase64);
            } else {
                // 否则使用原来的文本搜索
                originalShowTrademarkDetails(name);
            }
        }
        
        // 原始的显示商标详情函数
        function originalShowTrademarkDetails(name) {
            trademarkName = name;
            modal.style.display = "block";
            
            // 清除之前的数据
            clearCache();
            document.getElementById('modalTrademarkList').innerHTML = '';
            document.getElementById('modalTrademarkList').style.display = 'none';
            document.getElementById('modalError').style.display = 'none';
            document.getElementById('modalLoading').style.display = 'block';
            
            // 加载商标数据
            loadTrademarks(1);
        }
        
        // 使用图片和名称联合搜索商标
        async function searchTrademarkWithImage(name, imageBase64) {
            modal.style.display = "block";
            
            // 清除之前的数据
            clearCache();
            document.getElementById('modalTrademarkList').innerHTML = '';
            document.getElementById('modalTrademarkList').style.display = 'none';
            document.getElementById('modalError').style.display = 'none';
            document.getElementById('modalLoading').style.display = 'block';
            
            try {
                // 调用新的API端点，同时使用图片和名称搜索
                const response = await fetch('/api/search_trademark_with_image', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: name,
                        image: imageBase64,
                        top_k: 40
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const trademarkData = await response.json();
                
                // 检查API响应结构
                if (trademarkData.code !== 200) {
                    throw new Error(trademarkData.message || 'API调用失败');
                }
                
                // 验证数据结构
                if (!trademarkData.data) {
                    throw new Error('API响应缺少data字段');
                }
                
                // 检查是否有结果
                if (!trademarkData.data.result || trademarkData.data.result === "") {
                    // 没有结果的情况
                    allTrademarks = [];
                    hasMore = false;
                    currentPage = 1;
                    displayTrademarks();
                    return;
                }
                
                // 获取商标列表
                const trademarks = Array.isArray(trademarkData.data.result.list) ? trademarkData.data.result.list : [];
                
                // 只保留状态为"已注册"的商标
                const registeredTrademarks = trademarks.filter(trademark => {
                    // 检查多种可能的已注册状态表示
                    const status = trademark.status || '';
                    return status.includes('已注册') || status.includes('已注冊') || status === '已注册' || status === '已注冊';
                });
                
                // 设置缓存
                allTrademarks = registeredTrademarks;
                hasMore = false; // 对于图片搜索，我们只获取一次结果
                currentPage = 1;
                
                // 显示商标数据
                displayTrademarks();
            } catch (error) {
                console.error('获取商标信息失败:', error);
                document.getElementById('modalError').textContent = '获取商标信息失败: ' + error.message;
                document.getElementById('modalError').style.display = 'block';
                document.getElementById('modalLoading').style.display = 'none';
            } finally {
                document.getElementById('modalLoading').style.display = 'none';
                document.getElementById('modalLoadingMore').style.display = 'none';
            }
        }
        
        // 清除缓存
        function clearCache() {
            allTrademarks = [];
            currentPage = 1;
            hasMore = true;
        }
        
        // 加载更多商标数据
        async function loadMoreTrademarks() {
            if (!hasMore || isLoading) return;
            await loadTrademarks(currentPage + 1);
        }
        
        // 加载商标数据
        async function loadTrademarks(page) {
            if (isLoading) return;
            
            isLoading = true;
            if (page > 1) {
                document.getElementById('modalLoadingMore').style.display = 'block';
            }
            
            try {
                // 获取数据
                const trademarkData = await searchTrademark(trademarkName, page, pageSize);
                
                // 检查API响应结构
                if (trademarkData.code !== 200) {
                    throw new Error(trademarkData.message || 'API调用失败');
                }
                
                // 验证数据结构
                if (!trademarkData.data) {
                    throw new Error('API响应缺少data字段');
                }
                
                // 检查是否有结果
                if (!trademarkData.data.result || trademarkData.data.result === "") {
                    // 没有结果的情况
                    allTrademarks = [];
                    hasMore = false;
                    currentPage = page;
                    displayTrademarks();
                    return;
                }
                
                // 获取商标列表
                const trademarks = Array.isArray(trademarkData.data.result.list) ? trademarkData.data.result.list : [];
                
                // 只保留状态为"已注册"的商标
                const registeredTrademarks = trademarks.filter(trademark => {
                    // 检查多种可能的已注册状态表示
                    const status = trademark.status || '';
                    return status.includes('已注册') || status.includes('已注冊') || status === '已注册' || status === '已注冊';
                });
                
                // 添加到缓存中
                if (page === 1) {
                    allTrademarks = registeredTrademarks;
                } else {
                    allTrademarks = [...allTrademarks, ...registeredTrademarks];
                }
                
                // 判断是否还有更多数据
                hasMore = trademarks.length === parseInt(trademarkData.data.result.pagesize);
                
                currentPage = page;
                
                // 显示商标数据
                displayTrademarks();
            } catch (error) {
                console.error('获取商标信息失败:', error);
                document.getElementById('modalError').textContent = '获取商标信息失败: ' + error.message;
                document.getElementById('modalError').style.display = 'block';
                document.getElementById('modalLoading').style.display = 'none';
            } finally {
                isLoading = false;
                document.getElementById('modalLoading').style.display = 'none';
                document.getElementById('modalLoadingMore').style.display = 'none';
            }
        }
        
        // 显示商标数据
        function displayTrademarks() {
            // 显示商标列表
            const listContainer = document.getElementById('modalTrademarkList');
            
            if (currentPage === 1) {
                listContainer.innerHTML = '';
            }
            
            if (allTrademarks.length === 0 && currentPage === 1) {
                listContainer.innerHTML = '<div class="no-results">暂无已注册的商标数据</div>';
                listContainer.style.display = 'block';
                return;
            }
            
            // 显示商标
            allTrademarks.forEach(trademark => {
                // 避免重复添加
                if (!document.getElementById(`modal-trademark-${trademark.regno}`)) {
                    const trademarkItem = createTrademarkItem(trademark);
                    trademarkItem.id = `modal-trademark-${trademark.regno}`;
                    listContainer.appendChild(trademarkItem);
                }
            });
            
            listContainer.style.display = 'block';
        }
        
        // 搜索商标信息（通过后端接口）
        async function searchTrademark(keyword, page = 1, pageSize = 40) {
            const url = `/api/search_trademark?keyword=${keyword}&pagenum=${page}&pagesize=${pageSize}`;
            
            const response = await fetch(url, {
                method: 'GET'
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            return await response.json();
        }
        
        // 创建商标项目元素
        function createTrademarkItem(trademark) {
            const trademarkItem = document.createElement('div');
            trademarkItem.className = 'trademark-item';
            
            trademarkItem.innerHTML = `
                <div class="trademark-image">
                    <img src="${trademark.pic}" alt="商标图片" onerror="this.src=''">
                </div>
                <div class="trademark-info">
                    <h3>${trademark.name}</h3>
                    <div class="info-row">
                        <span class="info-label">注册号:</span>
                        <span>${trademark.regno}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">分类:</span>
                        <span>${trademark.classid}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">申请人:</span>
                        <span>${trademark.registrant}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">申请日期:</span>
                        <span>${trademark.appdate}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">状态:</span>
                        <span>${trademark.status || '未知'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">代理机构:</span>
                        <span>${trademark.agent || '无'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">联系方式:</span>
                        <span>${trademark.contact || trademark.agent || '无'}</span>
                    </div>
                </div>
            `;
            
            return trademarkItem;
        }
    </script>
</body>
</html>